package torrent;

import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.io.*;
import FileStructure.FileHandler;
import Peer.PeerDownloads;
import Peer.PeerRequest;
import Tools.cons;
import java.util.ArrayList;
import model.PeerEntity;

public class PeerGUI extends javax.swing.JFrame {

    int rowcount = 0;
    final static String Pause = "Pause";
    final static String Download = "Downloading";
    final static String Stop = "Stop";
    final static String Seeding = "Seeding";

    public PeerGUI() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        newTorrent = new javax.swing.JButton();
        openTorrent = new javax.swing.JButton();
        downloadButton = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        mysqlpass = new javax.swing.JPasswordField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "File Name", "Size", "Peer", "Seed"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        newTorrent.setText("Create New Torrent");
        newTorrent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                newTorrentActionPerformed(evt);
            }
        });

        openTorrent.setText("Open File Torrent");
        openTorrent.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                openTorrentActionPerformed(evt);
            }
        });

        downloadButton.setText("DOWNLOAD!");
        downloadButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                downloadButtonActionPerformed(evt);
            }
        });

        jButton2.setText("Stop Download");

        jButton3.setText("Clear List");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });

        jLabel1.setText("MySQL Password :");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(openTorrent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(newTorrent, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(105, 105, 105)
                                .addComponent(jLabel1)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(mysqlpass, javax.swing.GroupLayout.DEFAULT_SIZE, 114, Short.MAX_VALUE)
                                .addGap(142, 142, 142))
                            .addGroup(jPanel1Layout.createSequentialGroup()
                                .addGap(147, 147, 147)
                                .addComponent(jButton3)
                                .addGap(230, 230, 230)))
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                            .addComponent(jButton2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(downloadButton, javax.swing.GroupLayout.DEFAULT_SIZE, 126, Short.MAX_VALUE)))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 709, Short.MAX_VALUE))
                .addGap(55, 55, 55))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(newTorrent)
                        .addComponent(jButton3))
                    .addComponent(jButton2))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(openTorrent)
                        .addGap(27, 27, 27))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(downloadButton)
                            .addComponent(mysqlpass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)))
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 500, Short.MAX_VALUE)
                .addContainerGap())
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void openTorrentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_openTorrentActionPerformed
        // TODO add your handling code here:
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(null);
        
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                torrentFileDir = chooser.getSelectedFile().getParent() + "/";
                String torrentFileName = chooser.getSelectedFile().getName();
                fh.readTorrent(torrentFileDir, torrentFileName);
                System.out.println("fh torrent = "+fh.torrentName);
                addDisplay();
            } catch (Exception e) {
            }
        }
       
    }//GEN-LAST:event_openTorrentActionPerformed

    private void newTorrentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_newTorrentActionPerformed
        // TODO add your handling code here:\\
        JFileChooser chooser = new JFileChooser();
        int returnVal = chooser.showOpenDialog(null);
        FileHandler fh = new FileHandler();
        String torrentFileDir = "test/";
        File f = new File(torrentFileDir);
        if (!f.exists())
            f.mkdir();
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            try {
                String sharedFileDir = chooser.getSelectedFile().getParent() + "/";
                String sharedFileName = chooser.getSelectedFile().getName();
                fh.createTorrent(sharedFileDir, sharedFileName, torrentFileDir, cons.announceURL);
                //addDisplay(fh);
            } catch (Exception e) {
            }
        }

    }//GEN-LAST:event_newTorrentActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        jTable1.setValueAt(null, jTable1.getSelectedRow(), 0);
        jTable1.setValueAt(null, jTable1.getSelectedRow(), 1);
        jTable1.setValueAt(null, jTable1.getSelectedRow(), 2);
        jTable1.setValueAt(null, jTable1.getSelectedRow(), 3);

    }//GEN-LAST:event_jButton3ActionPerformed

    private void downloadButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_downloadButtonActionPerformed
        // TODO add your handling code here:
        try {
            String mpass = this.mysqlpass.getText();

            peer1 = new PeerEntity("127.0.0.1", 1234, true);
            pd = new PeerDownloads(peer1);
            pr = new PeerRequest(peer1,mpass);
             pr.torrentName = fh.torrentName;
             pr.dir = this.torrentFileDir;
             pd.dir = pr.dir;
             System.out.println("torrent name = " + pr.torrentName);
             peer1.request.file_name = fh.fileName;
            Thread td = new Thread(pd);
            Thread tr = new Thread(pr);
            tr.start();
            tr.sleep(1000);
            td.start();
            //tr.start();
        } catch (InterruptedException ex) {
            Logger.getLogger(PeerDownloads.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_downloadButtonActionPerformed

    public void addDisplay() {
        jTable1.setValueAt(fh.fileName, rowcount, 0);       // Nama File
        jTable1.setValueAt(fh.fileLength, rowcount, 1);     // File Size
        int peer = Integer.parseInt(fh.complete_value) + Integer.parseInt(fh.incomplete_value);
        jTable1.setValueAt(peer, rowcount, 2);              // Banyaknya peer
        jTable1.setValueAt(fh.complete_value, rowcount, 3); // Banyaknya seed (complete)
        ++rowcount;
    }

    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                new PeerGUI().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton downloadButton;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JPasswordField mysqlpass;
    private javax.swing.JButton newTorrent;
    private javax.swing.JButton openTorrent;
    // End of variables declaration//GEN-END:variables
    private boolean stop = false;
    PeerEntity peer1;
    PeerDownloads pd;
    PeerRequest pr;
    FileHandler fh = new FileHandler();
    String torrentFileDir;
    ArrayList<PeerRequest> arrayPeer = new ArrayList<PeerRequest>();
}
